﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace WpfWordsLearner.Helpers
{
	public static class CommandPropertyHelper
	{
		private static ICommand m_command = null;

		public static readonly DependencyProperty DropCommandProperty = DependencyProperty.RegisterAttached("DropCommand",
			typeof(ICommand),
			typeof(CommandPropertyHelper),
			new PropertyMetadata(null, OnDropCommandChange));

		public static void SetDropCommand(DependencyObject source, ICommand value)
		{
			source.SetValue(DropCommandProperty, value);
		}

		public static ICommand GetDropCommand(DependencyObject source)
		{
			return (ICommand)source.GetValue(DropCommandProperty);
		}

		private static void OnDropCommandChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			m_command = e.NewValue as ICommand;
			UIElement uiElement = d as UIElement;

			if (e.OldValue != null && uiElement != null)
			{
				uiElement.RemoveHandler(UIElement.DropEvent, new DragEventHandler(OnDrop));
				//uiElement.Drop -= OnDrop;
			}

			if (m_command != null && uiElement != null)
			{
				uiElement.AddHandler(UIElement.DropEvent, new DragEventHandler(OnDrop));
				//uiElement.Drop += OnDrop;
			}
		}

		private static void OnDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(typeof(Model.WordsModel)))
			{
				object data = e.Data.GetData("WpfWordsLearner.Model.WordsModel", true);
				m_command.Execute(data);
				//m_command.Execute(e.Data);

				e.Effects = DragDropEffects.None;
				e.Handled = true;
			}
		}
	}
}